<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  // #ifdef APP-PLUS
  import permision from "@/js_sdk/wa-permission/permission.js"
  const trtc = uni.requireNativePlugin('tx-call');
  //#endif
  export default {
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo,
      }),
    },
    data() {
      return {
        calltype: 0,
      }
    },
    async onLaunch() {
      uni.hideTabBar();
      // #ifdef APP-PLUS
      // plus.navigator.setFullscreen(true)
      // plus.navigator.hideSystemNavigation()
      let platform = uni.getSystemInfoSync().platform
      if (platform == 'ios') {
        await this.judgeIosPermission('camera')
        await this.judgeIosPermission('record')
      } else {
        this.wakeLock()
        await this.requestAndroidPermission('android.permission.CAMERA')
        await this.requestAndroidPermission('android.permission.RECORD_AUDIO')
      }
      this.createGlobEvent()
      this.addListener()
      //#endif
      if (this.userInfo?.token?.token) {
        uni.showLoading()
        this.login(this.userInfo)
      }
    },
    onResize(e) {
      this.$store.state.global.systemInfo = uni.getSystemInfoSync()
    },
    onReady() {
      setTimeout(() => {
        this.$store.state.global.systemInfo = uni.getSystemInfoSync()
      }, 3000)
    },
    onShow() {
    },
    methods: {
      //允许程序后台运行
      wakeLock() {
        //Android
        var main = plus.android.runtimeMainActivity();
        var Context = plus.android.importClass("android.content.Context");
        var PowerManager = plus.android.importClass("android.os.PowerManager");
        var pm = main.getSystemService(Context.POWER_SERVICE);
        this.g_wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ANY_NAME");
        this.g_wakelock.acquire();
      },
      //结束程序后台运行  
      releaseWakeLock() {
        if (this.g_wakelock != null && this.g_wakelock.isHeld()) {
          this.g_wakelock.release();
          this.g_wakelock = null;
        }
      },
      async requestAndroidPermission(permisionID) {
        var result = await permision.requestAndroidPermission(permisionID)
        var strStatus
        if (result == 1) {
          strStatus = "已获得授权"
        } else if (result == 0) {
          strStatus = "未获得授权"
        } else {
          strStatus = "被永久拒绝权限"
        }
        return result
        // uni.showModal({
        //   content: permisionID + strStatus,
        //   showCancel: false
        // });
      },
      async judgeIosPermission(permisionID) {
        var result = await permision.judgeIosPermission(permisionID)
        var strStatus
        if (result == 1) {
          strStatus = "已获得授权"
        } else if (result == 0) {
          strStatus = "未获得授权"
        } else {
          strStatus = "被永久拒绝权限"
        }
        return result
        // uni.showModal({
        //   content: permisionID + strStatus,
        //   showCancel: false
        // });
      },
      login(info) {
        let {
          tencent_user_id
        } = info.user
        tencent_user_id = String(tencent_user_id)
        let obj = {
          identifier: tencent_user_id,
          expire: 259200
        }
        this.$http.getUserSig(obj).then(res => {
          let {
            userSig,
            sdkappid
          } = res.data
          // #ifdef APP-PLUS
          trtc.login({
            sdkAppId: sdkappid,
            userId: tencent_user_id,
            userSig,
          }, res => {
            console.log('login:', res);
          })
          //#endif
          uni.$app.login({
            userID: tencent_user_id,
            userSig: userSig
          }).then(() => {
            this.$store.commit('setRtcConfig', {
              userSig: userSig,
              sdkAppID: sdkappid || 1400607227,
              userID: tencent_user_id
            });
            uni.hideLoading()
            uni.switchTab({
              url: '/pages/index/main'
            })
            console.log('IM登陆了');
          }).catch(() => {})
        })
      },
      createGlobEvent() {
        console.log('创建全局来电监听事件')
        uni.$on('call', (e) => {
          console.log('call:', e);
          this.calltype = e.calltype
          uni.navigateTo({
            url: `/pages/conversation/conversation?type=${e.type}&user=${e.user}&calltype=${e.calltype}&group=${e.group}`,
            animationType: 'slide-in-bottom',
            animationDuration: 350,
            success: function(res) {},
            fail: function(res) {}
          })
        })
      },
      addListener() {
        trtc.addDelegate(result => {
          console.log(result);
          switch (result.type) {
            // 收到邀请
            case 'onInvited':
              this.calltype = result.calltype;
              let obj = {
                user: result.userId,
                type: 0,
                calltype: this.calltype
              };
              if (uni.getSystemInfoSync().platform == 'android') {
                trtc.screenOn(result => {
                  console.log(result);
                  uni.$emit("call", obj);
                });
              } else {
                console.log(123456);
                uni.$emit("call", obj);
              }
              break;
              //对方拒绝
            case 'onReject':
              if (uni.getSystemInfoSync().platform == 'android') {
                trtc.screenOff(result => {
                  console.log(result);
                });
              }
              uni.$emit("cancelled", {
                calltype: this.calltype
              });
              break;
              // 邀请取消 
            case 'onCancel':
              if (uni.getSystemInfoSync().platform == 'android') {
                trtc.screenOff(result => {
                  console.log(result);
                });
              }
              uni.$emit("cancelled", {
                calltype: this.calltype
              });
              break;
              // 邀请超时
            case 'onTimeOut':
              uni.showToast({
                title: '长时间无人接听'
              })
              if (uni.getSystemInfoSync().platform == 'android') {
                trtc.screenOff(result => {
                  console.log(result);
                });
              }
              uni.$emit("cancelled", {
                calltype: this.calltype
              });
              break;
            case 'onUserEnter':
              uni.$emit("onUserEnter", {
                user: result.userId,
                calltype: this.calltype
              });
              break;
            case 'onUserLeave':
              if (uni.getSystemInfoSync().platform == 'android') {
                trtc.screenOff(result => {
                  console.log(result);
                });

              }
              uni.$emit("cancelled", {
                calltype: this.calltype
              });
          }
        });
      }
    },
  }
</script>

<style lang="scss">
  @import "./common/base.scss"; // 快速开发样式
  @import "@/uni_modules/uview-ui/index.scss";
  .button-disabled {
    color: $dark-background !important;
    background-color: transparent !important;
  }

  .input-focus {
    /* #ifndef APP-NVUE */
    box-sizing: border-box;
    /* #endif */
    border-bottom: 1px solid $primary !important;
  }
</style>
